package com.example.myspringframework.core.convert.support;

import com.example.myspringframework.core.convert.converter.Converter;

/**
 * 字符串->Number类型的转换器
 */
public class StringToNumberConverter<T extends Number> implements Converter<String, T> {
    private final Class<T> targetType;
    public StringToNumberConverter(Class<T> targetType) {
        this.targetType = targetType;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T convert(String source) {
        if (source.isEmpty()) {
            return null;
        }
        // 转换成对应的数字类型
        if (targetType==Integer.class) {
            return (T) Integer.valueOf(source);
        } else if (targetType==Long.class) {
            return (T) Long.valueOf(source);
        }else if (targetType==Double.class) {
            return (T) Double.valueOf(source);
        }else if (targetType==Float.class) {
            return (T) Float.valueOf(source);
        } else {
            throw new IllegalArgumentException(
                    "Cannot convert String [" + source + "] to target class [" + targetType.getName() + "]");
        }
    }
}
